# -*-coding:utf-8-*-
from django import template
from app01.utils.search import Search
from django.utils.safestring import mark_safe
from app01.models import Tags, Avatars, Menu, Articles

# 注册
register = template.Library()


@register.inclusion_tag('my_tag/headers.html')
def banner(menu_name, article=None):
    if article:
        # 说明是文章详情页
        # 拿到文章封面
        cover = article.cover.url.url
        img_list = [cover]
        title = article.title
        slogan_list = [article.abstract[:30]]
        menu_time = 0
        return locals()
    menu_obj = Menu.objects.get(menu_title_en=menu_name)
    img_list = [i.url.url for i in menu_obj.menu_url.all()]
    menu_time = menu_obj.menu_time

    title = menu_obj.title
    slogan_list = menu_obj.abstract.replace(':', ';').replace('\n', ';').split(';')

    if not menu_obj.menu_rotation:
        # 如果不轮播i
        img_list = img_list[0:1]
        menu_time = 0

    if menu_obj.rotation:
        slogan_list = slogan_list[0:1]
    menu_time = menu_obj.menu_time
    return locals()


@register.simple_tag
def generate_order_html(request, key):
    order_list = []
    order = request.GET.get(key, '')  # 用于设置选择排序方式
    if key == 'order':
        order_list = [
            ('-create_date', '综合排序'),
            ('-change_date', '最新发布'),
            ('-collects_count', '最多收藏'),
            ('-comment_count', '最多评论'),
            ('-look_count', '最多浏览'),
        ]
    elif key == 'word':
        order = request.GET.getlist('word', '')
        order_list = [
            ([], '所有字數'),
            (['0', '100'], '0-100字'),
            (['100', '500'], '100-500字'),
            (['500', '1000'], '500-1000字'),
            (['1000', '1000000'], '1000以上'),
        ]
    elif key == 'tag':
        tag_list = Tags.objects.exclude(articles__isnull=True)
        order_list.append(('', '全部标签'))
        for tag in tag_list:
            order_list.append((tag.title, tag.title))

    query_params = request.GET.copy()
    order = Search(
        order=order,
        order_list=order_list,
        query_params=query_params,
        key=key
    )

    return mark_safe(order.order_html())


# 生成动态导航条
@register.simple_tag
def dynamic_nav(request):
    path = request.path_info
    path_dict = {
        '/': '首页',
        '/news/': '新闻',
        '/moods/': '心情',
        '/about/': '关于',
        '/search/': '文章搜索',
        '/history/': '回忆录',
    }
    nav_list = []

    for k, v in path_dict.items():

        if k == path:
            nav_list.append(f'<a href="{k}" class="active">{v}</a>')
            continue
        else:
            nav_list.append(f'<a href="{k}">{v}</a>')
    return mark_safe(''.join(nav_list))


@register.simple_tag
def generate_drawing(drawing: str):
    if not drawing:
        return ''
    drawing_list = drawing.replace(';', ';').replace('\n', ';').split(';')
    html_s = ''
    for i in drawing_list:
        html_s += f'<img @error="img_error" src="{i}" alt="">'
    return mark_safe(html_s)


@register.simple_tag
def generate_li(content: str):
    if not content:
        return ''
    content_list = content.replace(';', ';').replace('\n', ';').split(';')
    html_s = ''
    for i in content_list:
        html_s += f'<li>{i}</li>'
    return mark_safe(html_s)


# 计算某个分类的文章数
@register.simple_tag
def calculation_category_count(cid):
    article_query = Articles.objects.filter(category=cid)
    return article_query.count()
